package controller.admin;


import controller.Items.student;
import controller.Items.teacher;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.control.cell.TextFieldTableCell;
import javafx.scene.layout.AnchorPane;
import javafx.stage.Stage;
import javafx.util.Callback;
import sample.Admin.AdminAddTeacher;
import sql.JDBC_T;

import java.text.MessageFormat;
import java.util.Vector;
import java.util.regex.*;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class AdminTeacherController {
    @FXML
    private TableView adm_tblList_teacher;
    @FXML
    private Button adm_btn_search;
    @FXML
    private  TextField  adm_txfld_search;
    private Alert alert,alertwindow;
    public void initialize() throws SQLException {
        update(this.adm_tblList_teacher);
    }
    public void update(TableView tableView) throws SQLException {
        tableView.setEditable(true);
        String id,name,sex,office;
        String sql = "SELECT teacher.TID,teacher.Tname,teacher.Tsex,teacher.Troom\n" +
                "FROM teacher\n" +
                "GROUP BY teacher.TID;";
        JDBC_T jdbc_t = new JDBC_T();
        if(jdbc_t.is_conn()){
            System.out.println("查询教师信息成功!!!");
            PreparedStatement preparedStatement = jdbc_t.getConn().prepareStatement(sql);
            ResultSet resultSet = preparedStatement.executeQuery();
            ObservableList<teacher> all = FXCollections.observableArrayList();
            Vector<String > ids = new Vector<>();
            while(resultSet.next()){
                id = resultSet.getString("TID");
                sex = resultSet.getString("Tsex");
                name = resultSet.getString("Tname");
                office= resultSet.getString("Troom");
                all.add(new teacher(id,name,sex,office));
                ids.add(id);
            }
            ObservableList<TableColumn> cols=tableView.getColumns();
            TableColumn tid = cols.get(0);
            TableColumn tname = cols.get(1);
            TableColumn  tsex = cols.get(2);
            TableColumn  toffice = cols.get(3);
            TableColumn edit = cols.get(4);
            TableColumn modify = (TableColumn) edit.getColumns().get(0);
            TableColumn delete = (TableColumn)edit.getColumns().get(1);
            tid.setCellValueFactory(new PropertyValueFactory<teacher,String>("Tid"));
            tname.setCellValueFactory(new PropertyValueFactory<teacher,String>("Tname"));
            tsex.setCellValueFactory(new PropertyValueFactory<teacher,String>("Tsex"));
            toffice.setCellValueFactory(new PropertyValueFactory<teacher,String>("Toffice"));

            modify.setCellFactory((col)-> {TableCell<teacher, String> cell = new TableCell<teacher, String>() {
                @Override
                protected void updateItem(String item, boolean empty) {
                    super.updateItem(item, empty);
                    Button button = new Button("修改");
                    button.setOnAction((col) -> {
                                String sql ="";
                                teacher te =all.get(getIndex());
                                if(ids.contains(te.getTid())) {
//                                    sql = MessageFormat.format("update teacher  set Troom=\"{0}\", Tname=\"{1}\", Tsex=\"{2}\" "
//                                            +"where Tid = \"{3}\"", te.getToffice(),te.getTname(),te.getTsex(),te.getTid());
                                    sql = MessageFormat.format("Update teacher set Tname={0}{1}{0}, Tsex={0}{2}{0}, Troom={0}{3}{0}  where Tid = {0}{4}{0} ",'"' ,te.getTname(),te.getTsex(),te.getToffice(),te.getTid());
                                    System.out.println(sql);
                                    System.out.println(te.tsexProperty());
                                    try {
                                        preparedStatement.execute(sql);
                                    } catch (SQLException sqlException) {
                                        sqlException.printStackTrace();
                                    }
                                }else{
                                    alertwindow = new Alert(Alert.AlertType.WARNING);
                                    alertwindow.setContentText("请注意是否修改了id");
                                    alertwindow.showAndWait();

                                }
                            }
                            );
                            if (empty) {
                                //如果此列为空默认不添加元素
                                setText(null);
                                setGraphic(null); }
                            else { this.setGraphic(button); }
                        }
            };
                return cell;
            });
            delete.setCellFactory((col)-> {TableCell<teacher, String> cell = new TableCell<teacher, String>() {
                @Override
                protected void updateItem(String item, boolean empty) {
                    super.updateItem(item, empty);
                    Button button = new Button("删除");
                    button.setOnAction((col)->{
                                System.out.println(getIndex());
                                teacher del_tea = all.get(getIndex());
                                String tid1=del_tea.getTid();
                                String sql1 = MessageFormat.format("Delete from teacher where TID = {0}{1}{0}",'"',tid1);
                                System.out.println(sql1);

                                try {
                                    preparedStatement.execute(sql1);
                                } catch (SQLException sqlException) {
                                    sqlException.printStackTrace();
                                }
                                System.out.println(sql);
                                all.remove(del_tea);

                            }
                    );
                    if (empty) {
                        //如果此列为空默认不添加元素
                        setText(null);
                        setGraphic(null); }
                    else { this.setGraphic(button); }
                }
            };
                return cell;
            });
            tableView.setItems(all);

            tid.setCellFactory(TextFieldTableCell.forTableColumn());
            
            tname.setCellFactory(TextFieldTableCell.forTableColumn());
            tsex.setCellFactory(TextFieldTableCell.forTableColumn());
            toffice.setCellFactory(TextFieldTableCell.forTableColumn());
//
//            tid.setOnEditCommit(
//                    (TableColumn.CellEditEvent<teacher, String> t) -> {
//                        ((teacher) t.getTableView().getItems().get(
//                                t.getTablePosition().getRow())
//                        ).setTid(t.getNewValue());
//                    });



        }
    }
    public void search(){
        alert = new Alert(Alert.AlertType.WARNING);
        String str = adm_txfld_search.getText();
        String reg1 = "^[0-9]*$";//三位数字 教师号
        String reg2 = "[\\u4e00-\\u9fa5]{1,4}";
        AnchorPane anchorPane =new AnchorPane();
        TableView resulttable=new TableView();
        TableColumn tid,tname,tsex,toffice;
        tid = new TableColumn("Tid");
        tname = new TableColumn("Tname");
        tsex = new TableColumn("Tsex");
        toffice = new TableColumn("Toffice");
        resulttable.getColumns().addAll(tid,tname,tsex,toffice);
        tid.setCellValueFactory(new PropertyValueFactory<>("Tid"));
        tname.setCellValueFactory(new PropertyValueFactory<>("Tname"));
        tsex.setCellValueFactory(new PropertyValueFactory<>("Tsex"));
        toffice.setCellValueFactory(new PropertyValueFactory<>("Toffice"));
        ObservableList<teacher> teachers = adm_tblList_teacher.getItems();
        ObservableList<teacher> result=FXCollections.observableArrayList();
        boolean ismatch;
        if(str.isEmpty()){
            alert.setContentText("请输入内容，搜索不能为空!!!");
            alert.showAndWait();

        }
        else  if(Pattern.matches(reg1,str)){
            for (teacher i: teachers
                 ) {
                if(i.getTid().equals(str)){
                    result.add(i);
                }
            }
            if(result.isEmpty()){
                alert.setContentText("没有搜索到此老师");
                alert.showAndWait();
            }else {
                anchorPane.setPrefWidth(300);
                anchorPane.setPrefHeight(300);
                resulttable.setItems(result);
                anchorPane.getChildren().add(resulttable);
                Scene scene = new Scene(anchorPane);
                Stage newstage = new Stage();
                newstage.setScene(scene);
                newstage.show();
            }

        }
        else if(Pattern.matches(reg2,str)){
            for (teacher i: teachers
            ) {
                if(i.getTname().equals(str)){
                    result.add(i);
                }
            }
            if(result.isEmpty()){
                alert.setContentText("没有搜索到此老师");
                alert.showAndWait();
            }else {
                anchorPane.setPrefWidth(300);
                anchorPane.setPrefHeight(300);
                resulttable.setItems(result);
                anchorPane.getChildren().add(resulttable);
                Scene scene = new Scene(anchorPane);
                Stage newstage = new Stage();
                newstage.setScene(scene);
                newstage.show();
            }
        }
        else {
            alert.setContentText("请确认输入正确");
            alert.showAndWait();
        }

    }
    public void addtea() throws Exception {
        new AdminAddTeacher().start(new Stage());
    }
}
